﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Transactions;
using System.Data.SqlClient;

using Global.Class.Library;
using DataTransferObject;
using DataTransferObject.MetaDataList;
using DataAccessLayer;
using DataAccessLayer.MetaDataList;
using DataAccessLayer.MetaDataList.ListSalesmenNameDTSTableAdapters;

namespace BusinessLogicLayer.MetaDataList
{
    public class ListSalesmenNameBLL : NotifyPropertyChangeObject
    {
        public GlobalEnum.TaskID TaskID { get { return GlobalEnum.TaskID.ListSalesmenName; } }

        private UserInformation userOrganization;

        private ListSalesmenNameMaster listSalesmenNameMaster;

        private BindingList<ListSalesmenAddressArea> listSalesmenAddressAreaList;
        private BindingList<ListSalesmenCommodity> listSalesmenCommodityList;
        private BindingList<ListSalesmenCustomer> listSalesmenCustomerList;
        private BindingList<ListSalesmenItemClass> listSalesmenItemClassList;


        public ListSalesmenNameBLL()
        {
            try
            {
                if (GlobalVariables.shouldRestoreProcedure) RestoreProcedure();


                userOrganization = new UserInformation();

                listSalesmenNameMaster = new ListSalesmenNameMaster();

                this.listSalesmenAddressAreaList = new BindingList<ListSalesmenAddressArea>();
                this.listSalesmenCommodityList = new BindingList<ListSalesmenCommodity>();
                this.listSalesmenCustomerList = new BindingList<ListSalesmenCustomer>();
                this.listSalesmenItemClassList = new BindingList<ListSalesmenItemClass>();

                GlobalDefaultValue.Apply(this);


                this.ListSalesmenNameMaster.PropertyChanged += new PropertyChangedEventHandler(ListSalesmenNameMaster_PropertyChanged);

                this.ListSalesmenAddressAreaList.ListChanged += new ListChangedEventHandler(ListSalesmenAddressAreaList_ListChanged);
                this.ListSalesmenCommodityList.ListChanged += new ListChangedEventHandler(ListSalesmenCommodityList_ListChanged);
                this.ListSalesmenCustomerList.ListChanged += new ListChangedEventHandler(ListSalesmenCustomerList_ListChanged);
                this.ListSalesmenItemClassList.ListChanged += new ListChangedEventHandler(ListSalesmenItemClassList_ListChanged);

            }
            catch (Exception exception)
            {
                throw exception;
            }
        }

        private void ListSalesmenNameMaster_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.SetDirty();
        }

        private void ListSalesmenAddressAreaList_ListChanged(object sender, ListChangedEventArgs e)
        {
            this.SetDirty();
        }

        private void ListSalesmenCommodityList_ListChanged(object sender, ListChangedEventArgs e)
        {
            this.SetDirty();
        }

        private void ListSalesmenCustomerList_ListChanged(object sender, ListChangedEventArgs e)
        {
            this.SetDirty();
        }

        private void ListSalesmenItemClassList_ListChanged(object sender, ListChangedEventArgs e)
        {
            this.SetDirty();
        }
       




        #region <Adapter>

        private ListSalesmenNameListingTableAdapter listingTableAdapter;
        protected ListSalesmenNameListingTableAdapter ListingTableAdapter
        {
            get
            {
                if (listingTableAdapter == null) listingTableAdapter = new ListSalesmenNameListingTableAdapter();
                return listingTableAdapter;
            }
        }

        private ListSalesmenNameTableAdapter masterTableAdapter;
        protected ListSalesmenNameTableAdapter MasterTableAdapter
        {
            get
            {
                if (masterTableAdapter == null) masterTableAdapter = new ListSalesmenNameTableAdapter();
                return masterTableAdapter;
            }
        }

        private ListSalesmenAddressAreaTableAdapter addressAreaTableAdapter;
        protected ListSalesmenAddressAreaTableAdapter AddressAreaTableAdapter
        {
            get
            {
                if (addressAreaTableAdapter == null) addressAreaTableAdapter = new ListSalesmenAddressAreaTableAdapter();
                return addressAreaTableAdapter;
            }
        }


        private ListSalesmenCommodityTableAdapter commodityTableAdapter;
        protected ListSalesmenCommodityTableAdapter CommodityTableAdapter
        {
            get
            {
                if (commodityTableAdapter == null) commodityTableAdapter = new ListSalesmenCommodityTableAdapter();
                return commodityTableAdapter;
            }
        }

        
        private ListSalesmenCustomerTableAdapter customerTableAdapter;
        protected ListSalesmenCustomerTableAdapter CustomerTableAdapter
        {
            get
            {
                if (customerTableAdapter == null) customerTableAdapter = new ListSalesmenCustomerTableAdapter();
                return customerTableAdapter;
            }
        }

        private ListSalesmenItemClassTableAdapter itemClassTableAdapter;
        protected ListSalesmenItemClassTableAdapter ItemClassTableAdapter
        {
            get
            {
                if (itemClassTableAdapter == null) itemClassTableAdapter = new ListSalesmenItemClassTableAdapter();
                return itemClassTableAdapter;
            }
        }


        #endregion <Adapter>


        #region <Storage>

        public UserInformation UserOrganization
        {
            get { return this.userOrganization; }
            set { this.userOrganization = value; }
        }

        public ListSalesmenNameDTS.ListSalesmenNameListingDataTable ListSalesmenNameListing()
        {
            return this.ListingTableAdapter.GetData();
        }

        public ListSalesmenNameMaster ListSalesmenNameMaster
        {
            get { return this.listSalesmenNameMaster; }
        }

        public BindingList<ListSalesmenAddressArea> ListSalesmenAddressAreaList
        {
            get { return this.listSalesmenAddressAreaList; }
        }

        public BindingList<ListSalesmenCommodity> ListSalesmenCommodityList
        {
            get { return this.listSalesmenCommodityList; }
        }

        public BindingList<ListSalesmenCustomer> ListSalesmenCustomerList
        {
            get { return this.listSalesmenCustomerList; }
        }

        public BindingList<ListSalesmenItemClass> ListSalesmenItemClassList
        {
            get { return this.listSalesmenItemClassList; }
        }


        #endregion <Storage>


        #region Properties

        #region <Primary Key>

        public int SalesmenID   //Primary Key
        {
            get { return this.ListSalesmenNameMaster.SalesmenID; }
            private set
            {
                if (this.ListSalesmenNameMaster.SalesmenID != value)
                {
                    this.StopTracking();

                    this.ListSalesmenNameMaster.SalesmenID = value;

                    this.ListSalesmenNameGetMaster();
                    this.ListSalesmenNameGetAddressArea();
                    this.ListSalesmenNameGetCommodity();
                    this.ListSalesmenNameGetCustomer();
                    this.ListSalesmenNameGetItemClass();
                    

                    this.StartTracking();
                    this.Reset();
                }

            }
        }

        #endregion <Primary Key>

        private void ListSalesmenNameGetMaster()
        {
            if (this.SalesmenID > 0)
            {
                ListSalesmenNameDTS.ListSalesmenNameDataTable masterDataTable = this.MasterTableAdapter.GetData(this.SalesmenID);

                if (masterDataTable.Count > 0)
                {
                    this.ListSalesmenNameMaster.StopTracking();

                    this.ListSalesmenNameMaster.EntryDate = masterDataTable[0].EntryDate;
                    this.ListSalesmenNameMaster.Birthday = masterDataTable[0].Birthday;
                    this.ListSalesmenNameMaster.HiredDate = masterDataTable[0].HiredDate;

                    this.ListSalesmenNameMaster.SalesmenCategoryID = masterDataTable[0].SalesmenCategoryID;
                    this.ListSalesmenNameMaster.SalesmenTypeID = masterDataTable[0].SalesmenTypeID;
                    this.ListSalesmenNameMaster.SalesmenTitleID = masterDataTable[0].SalesmenTitleID;  

                    this.ListSalesmenNameMaster.Description = masterDataTable[0].Description;
                    this.ListSalesmenNameMaster.DescriptionDEI = masterDataTable[0].DescriptionDEI;
                    this.ListSalesmenNameMaster.DescriptionZUL = masterDataTable[0].DescriptionZUL;
                    this.ListSalesmenNameMaster.DescriptionOfficial = masterDataTable[0].DescriptionOfficial;
                    this.ListSalesmenNameMaster.DescriptionLastName = masterDataTable[0].DescriptionLastName;
                    this.ListSalesmenNameMaster.DescriptionOriginal = masterDataTable[0].DescriptionOriginal;
                    this.ListSalesmenNameMaster.JobTitle = masterDataTable[0].JobTitle;
                    this.ListSalesmenNameMaster.ResidentAddress = masterDataTable[0].ResidentAddress;
                    this.ListSalesmenNameMaster.IdentifyNumber = masterDataTable[0].IdentifyNumber;
                    this.ListSalesmenNameMaster.SecurityID = masterDataTable[0].SecurityID;
                    this.ListSalesmenNameMaster.Telephone = masterDataTable[0].Telephone;
                    this.ListSalesmenNameMaster.Other = masterDataTable[0].Other;
                    this.ListSalesmenNameMaster.EMail = masterDataTable[0].EMail;
                    this.ListSalesmenNameMaster.EmployeePicture = masterDataTable[0].EmployeePicture;

                    this.ListSalesmenNameMaster.Female = masterDataTable[0].Female;
                    this.ListSalesmenNameMaster.Married = masterDataTable[0].Married;
                    this.ListSalesmenNameMaster.SalesmenCommodityAll = masterDataTable[0].SalesmenCommodityAll;
           

                    this.ListSalesmenNameMaster.InActive = masterDataTable[0].InActive;

                    this.ListSalesmenNameMaster.StartTracking();

                    this.ListSalesmenNameMaster.Reset();

                    this.UserOrganization.UserID = masterDataTable[0].UserID;
                    this.UserOrganization.UserOrganizationID = masterDataTable[0].UserOrganizationID;
                }
                else throw new System.ArgumentException("Insufficient get data");
            }
            else
            {
                GlobalDefaultValue.Apply(this.ListSalesmenNameMaster);
                this.ListSalesmenNameMaster.EntryDate = DateTime.Today;
                this.ListSalesmenNameMaster.Reset();
            }
        }


        private void ListSalesmenNameGetAddressArea()
        {
            this.listSalesmenAddressAreaList.RaiseListChangedEvents = false;
            this.listSalesmenAddressAreaList.Clear();
            if (this.SalesmenID >= 0)
            {

                ListSalesmenNameDTS.ListSalesmenAddressAreaDataTable detailDataTable = this.AddressAreaTableAdapter.GetData(this.SalesmenID);

                if (detailDataTable.Count > 0)
                {
                    foreach (ListSalesmenNameDTS.ListSalesmenAddressAreaRow detailRow in detailDataTable.Rows)
                    {
                        this.listSalesmenAddressAreaList.Add(new ListSalesmenAddressArea(detailRow.AddressAreaID, detailRow.Description, detailRow.Other, detailRow.InActive));
                    }
                }
            }
            this.listSalesmenAddressAreaList.RaiseListChangedEvents = true;
            this.listSalesmenAddressAreaList.ResetBindings();
        }


        private void ListSalesmenNameGetCommodity()
        {
            this.listSalesmenCommodityList.RaiseListChangedEvents = false;
            this.listSalesmenCommodityList.Clear();
            if (this.SalesmenID >= 0)
            {

                ListSalesmenNameDTS.ListSalesmenCommodityDataTable detailDataTable = this.CommodityTableAdapter.GetData(this.SalesmenID);

                if (detailDataTable.Count > 0)
                {
                    foreach (ListSalesmenNameDTS.ListSalesmenCommodityRow detailRow in detailDataTable.Rows)
                    {
                        this.listSalesmenCommodityList.Add(new ListSalesmenCommodity(detailRow.CommodityID, detailRow.Description, detailRow.Other, detailRow.InActive));
                    }
                }
            }
            this.listSalesmenCommodityList.RaiseListChangedEvents = true;
            this.listSalesmenCommodityList.ResetBindings();
        }



        private void ListSalesmenNameGetCustomer()
        {
            this.listSalesmenCustomerList.RaiseListChangedEvents = false;
            this.listSalesmenCustomerList.Clear();
            if (this.SalesmenID >= 0)
            {

                ListSalesmenNameDTS.ListSalesmenCustomerDataTable detailDataTable = this.CustomerTableAdapter.GetData(this.SalesmenID);

                if (detailDataTable.Count > 0)
                {
                    foreach (ListSalesmenNameDTS.ListSalesmenCustomerRow detailRow in detailDataTable.Rows)
                    {
                        this.listSalesmenCustomerList.Add(new ListSalesmenCustomer(detailRow.CustomerID, detailRow.Description, detailRow.Other, detailRow.InActive));
                    }
                }
            }
            this.listSalesmenCustomerList.RaiseListChangedEvents = true;
            this.listSalesmenCustomerList.ResetBindings();
        }


        private void ListSalesmenNameGetItemClass()
        {
            this.listSalesmenItemClassList.RaiseListChangedEvents = false;
            this.listSalesmenItemClassList.Clear();
            if (this.SalesmenID >= 0)
            {

                ListSalesmenNameDTS.ListSalesmenItemClassDataTable detailDataTable = this.ItemClassTableAdapter.GetData(this.SalesmenID);

                if (detailDataTable.Count > 0)
                {
                    foreach (ListSalesmenNameDTS.ListSalesmenItemClassRow detailRow in detailDataTable.Rows)
                    {
                        this.listSalesmenItemClassList.Add(new ListSalesmenItemClass(detailRow.ItemClassID, detailRow.Description, detailRow.Other, detailRow.InActive));
                    }
                }
            }
            this.listSalesmenItemClassList.RaiseListChangedEvents = true;
            this.listSalesmenItemClassList.ResetBindings();
        }



        #endregion Properties





        #region Object Permission

        public override bool IsValid
        {
            get
            {
                List<ListSalesmenAddressArea> inValidListSalesmenAddressArea = this.ListSalesmenAddressAreaList.Where(listSalesmenNameDetail => !listSalesmenNameDetail.IsValid).ToList();
                return this.ListSalesmenNameMaster.IsValid && inValidListSalesmenAddressArea.Count == 0;
            }
        }

        public bool ReadOnly
        {
            get
            {
                try
                {
                    return GlobalUserPermission.GetUserReadOnly(GlobalVariables.GlobalUserInformation.UserID, this.TaskID);
                }
                catch
                {
                    return true;
                }
            }
        }

        public bool Editable
        {
            get
            {
                try
                {
                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, this.TaskID, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("ListSalesmenNameEditable", this.SalesmenID);
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool Verifiable
        {
            get
            {
                try
                {
                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, GlobalEnum.TaskID.ListSalesmenNameVerifiable, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("ListSalesmenNameEditable", this.SalesmenID);
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool Unverifiable
        {
            get
            {
                try
                {
                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, GlobalEnum.TaskID.ListSalesmenNameUnverifiable, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("ListSalesmenNameEditable", this.SalesmenID);
                }
                catch
                {
                    return false;
                }
            }
        }


        #endregion Object Permission






        public void Fill(int customerTypeID)
        {
            if (this.SalesmenID == customerTypeID) this.SalesmenID = -1; //Enforce to reload
            this.SalesmenID = customerTypeID;
        }

        public void New()
        {
            if (this.SalesmenID == 0) this.SalesmenID = -1;
            this.SalesmenID = 0;
        }

        public void Edit()
        {

        }

        #region Save & Delete Method


        public bool Save()
        {
            int customerTypeID = 0;

            try
            {

                if (!this.SaveValidate()) throw new System.ArgumentException("Insufficient save", "Save validate");

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (this.ReadOnly) throw new System.ArgumentException("Insufficient save", "Uneditable");

                    if (!this.SaveMaster(ref customerTypeID)) throw new System.ArgumentException("Insufficient save", "Save master");

                    if (!this.SaveDetail(customerTypeID)) throw new System.ArgumentException("Insufficient save", "Save detail");


                    SQLDatabase.ExecuteNonQuery("DELETE FROM ListSalesmenCategoryFull "); //NHAM MUC DICH UPDATE SUPERVISOR
                    SQLDatabase.ExecuteNonQuery("INSERT INTO ListSalesmenCategoryFull (SalesmenCategoryID, Description, SupervisorCode, SupervisorName, SalesmenCategoryID1, Description1, SalesmenCategoryID2, Description2, SalesmenCategoryID3, Description3, SalesmenCategoryID4, Description4, SalesmenCategoryID5, Description5, SalesmenCategoryID6, Description6, SalesmenCategoryID7, Description7, SalesmenCategoryID8, Description8, SalesmenCategoryID9, Description9) SELECT SalesmenCategoryID, Description, SupervisorCode, SupervisorName, SalesmenCategoryID1, Description1, SalesmenCategoryID2, Description2, SalesmenCategoryID3, Description3, SalesmenCategoryID4, Description4, SalesmenCategoryID5, Description5, SalesmenCategoryID6, Description6, SalesmenCategoryID7, Description7, SalesmenCategoryID8, Description8, SalesmenCategoryID9, Description9 FROM VWListSalesmenCategory");


                    transactionScope.Complete();
                }

                this.Fill(customerTypeID);
                return true;
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
        }


        public bool Delete()
        {
            if (this.listSalesmenNameMaster.SalesmenID <= 0) return false;

            try
            {

                if (!this.SaveValidate()) throw new System.ArgumentException("Insufficient delete", "Delete validate");

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (!this.Editable) throw new System.ArgumentException("Insufficient delete", "Uneditable");

                    if (!this.SaveUndo(this.listSalesmenNameMaster.SalesmenID)) throw new System.ArgumentException("Insufficient delete", "Delete detail");

                    if (this.MasterTableAdapter.Delete(this.listSalesmenNameMaster.SalesmenID) != 1) throw new System.ArgumentException("Insufficient delete", "Delete master");

                    transactionScope.Complete();
                }
                this.Fill(0);
                return true;
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
        }


        private bool SaveValidate()
        {
            ExceptionTable exceptionTable = new ExceptionTable(new string[2, 2] { { "ExceptionCategory", "System.String" }, { "ExceptionDescription", "System.String" } });

            this.UserOrganization = GlobalUserPermission.GetUserInformation(this.UserOrganization.UserID, this.ListSalesmenNameMaster.EntryDate);

            if (this.UserOrganization.UserID <= 0 || this.UserOrganization.UserOrganizationID <= 0) exceptionTable.AddException(new string[] { GlobalVariables.stringFieldRequired, "User information" });

            if (exceptionTable.Table.Rows.Count <= 0 && this.IsValid) return true; else throw new CustomException("Save validate", exceptionTable.Table);
        }


        private bool SaveMaster(ref int customerTypeID)
        {
            ListSalesmenNameDTS.ListSalesmenNameDataTable masterDataTable;
            ListSalesmenNameDTS.ListSalesmenNameRow masterRow;

            if (this.listSalesmenNameMaster.SalesmenID <= 0) //Add
            {
                masterDataTable = new ListSalesmenNameDTS.ListSalesmenNameDataTable();
                masterRow = masterDataTable.NewListSalesmenNameRow();
            }
            else //Edit
            {
                if (!this.SaveUndo(listSalesmenNameMaster.SalesmenID)) throw new System.ArgumentException("Insufficient save", "Save undo");
                masterDataTable = this.MasterTableAdapter.GetData(listSalesmenNameMaster.SalesmenID);
                if (masterDataTable.Count > 0) masterRow = masterDataTable[0]; else throw new System.ArgumentException("Insufficient save", "Get for edit");
            }

            masterRow.EntryDate = this.listSalesmenNameMaster.EntryDate;
            masterRow.Birthday = this.listSalesmenNameMaster.Birthday;
            masterRow.HiredDate = this.listSalesmenNameMaster.HiredDate;

            masterRow.SalesmenCategoryID = this.listSalesmenNameMaster.SalesmenCategoryID;
            masterRow.SalesmenTypeID = this.listSalesmenNameMaster.SalesmenTypeID;
            masterRow.SalesmenTitleID = this.listSalesmenNameMaster.SalesmenTitleID;

            masterRow.Description = this.listSalesmenNameMaster.Description;
            masterRow.DescriptionDEI = this.listSalesmenNameMaster.DescriptionDEI;
            masterRow.DescriptionZUL = this.listSalesmenNameMaster.DescriptionZUL;
            masterRow.DescriptionOfficial = this.listSalesmenNameMaster.DescriptionOfficial;
            masterRow.DescriptionLastName = this.listSalesmenNameMaster.DescriptionLastName;
            masterRow.DescriptionOriginal = this.listSalesmenNameMaster.DescriptionOriginal;
            masterRow.JobTitle = this.listSalesmenNameMaster.JobTitle;
            masterRow.ResidentAddress = this.listSalesmenNameMaster.ResidentAddress;
            masterRow.IdentifyNumber = this.listSalesmenNameMaster.IdentifyNumber;
            masterRow.SecurityID = this.listSalesmenNameMaster.SecurityID;
            masterRow.Telephone = this.listSalesmenNameMaster.Telephone;
            masterRow.Other = this.listSalesmenNameMaster.Other;
            masterRow.EMail = this.listSalesmenNameMaster.EMail;
            masterRow.EmployeePicture = this.listSalesmenNameMaster.EmployeePicture;

            masterRow.Female = this.listSalesmenNameMaster.Female;
            masterRow.Married = this.listSalesmenNameMaster.Married;
            masterRow.SalesmenCommodityAll = this.listSalesmenNameMaster.SalesmenCommodityAll;


            masterRow.InActive = this.listSalesmenNameMaster.InActive;

            masterRow.UserID = this.UserOrganization.UserID;
            masterRow.UserOrganizationID = this.UserOrganization.UserOrganizationID;

            if (this.listSalesmenNameMaster.SalesmenID <= 0) masterDataTable.AddListSalesmenNameRow(masterRow);

            int rowsAffected = this.MasterTableAdapter.Update(masterRow);

            customerTypeID = masterRow.SalesmenID;

            return rowsAffected == 1;

        }


        private bool SaveDetail(int customerTypeID)
        {
            int serialID = 0; int rowsAffected = 0;


            #region <Address Area>

            serialID = 0;

            ListSalesmenNameDTS.ListSalesmenAddressAreaDataTable addressAreaDataTable = new ListSalesmenNameDTS.ListSalesmenAddressAreaDataTable();

            foreach (ListSalesmenAddressArea listSalesmenNameDetail in this.ListSalesmenAddressAreaList)
            {
                ListSalesmenNameDTS.ListSalesmenAddressAreaRow detailRow = addressAreaDataTable.NewListSalesmenAddressAreaRow();

                detailRow.SalesmenID = customerTypeID;
                detailRow.SerialID = ++serialID;

                detailRow.AddressAreaID = listSalesmenNameDetail.AddressAreaID;
                detailRow.Description = listSalesmenNameDetail.Description;

                detailRow.Other = listSalesmenNameDetail.Other;

                detailRow.InActive = listSalesmenNameDetail.InActive;

                addressAreaDataTable.AddListSalesmenAddressAreaRow(detailRow);
            }

            rowsAffected = this.AddressAreaTableAdapter.Update(addressAreaDataTable);
            if (rowsAffected != this.listSalesmenAddressAreaList.Count) throw new System.ArgumentException("Insufficient save", "Save detail");


            #endregion <Address Area>


            #region <Commodity>

            serialID = 0;

            ListSalesmenNameDTS.ListSalesmenCommodityDataTable commodityDataTable = new ListSalesmenNameDTS.ListSalesmenCommodityDataTable();

            foreach (ListSalesmenCommodity listSalesmenNameDetail in this.ListSalesmenCommodityList)
            {
                ListSalesmenNameDTS.ListSalesmenCommodityRow detailRow = commodityDataTable.NewListSalesmenCommodityRow();

                detailRow.SalesmenID = customerTypeID;
                detailRow.SerialID = ++serialID;

                detailRow.CommodityID = listSalesmenNameDetail.CommodityID;
                detailRow.Description = listSalesmenNameDetail.Description;

                detailRow.Other = listSalesmenNameDetail.Other;

                detailRow.InActive = listSalesmenNameDetail.InActive;

                commodityDataTable.AddListSalesmenCommodityRow(detailRow);
            }

            rowsAffected = this.CommodityTableAdapter.Update(commodityDataTable);
            if (rowsAffected != this.listSalesmenCommodityList.Count) throw new System.ArgumentException("Insufficient save", "Save detail");


            #endregion <Commodity>


            #region <Customer>

            serialID = 0;

            ListSalesmenNameDTS.ListSalesmenCustomerDataTable customerDataTable = new ListSalesmenNameDTS.ListSalesmenCustomerDataTable();

            foreach (ListSalesmenCustomer listSalesmenNameDetail in this.ListSalesmenCustomerList)
            {
                ListSalesmenNameDTS.ListSalesmenCustomerRow detailRow = customerDataTable.NewListSalesmenCustomerRow();

                detailRow.SalesmenID = customerTypeID;
                detailRow.SerialID = ++serialID;

                detailRow.CustomerID = listSalesmenNameDetail.CustomerID;
                detailRow.Description = listSalesmenNameDetail.Description;

                detailRow.Other = listSalesmenNameDetail.Other;

                detailRow.InActive = listSalesmenNameDetail.InActive;

                customerDataTable.AddListSalesmenCustomerRow(detailRow);
            }

            rowsAffected = this.CustomerTableAdapter.Update(customerDataTable);
            if (rowsAffected != this.listSalesmenCustomerList.Count) throw new System.ArgumentException("Insufficient save", "Save detail");


            #endregion <Customer>


            #region <Item Class>

            serialID = 0;

            ListSalesmenNameDTS.ListSalesmenItemClassDataTable itemClassDataTable = new ListSalesmenNameDTS.ListSalesmenItemClassDataTable();

            foreach (ListSalesmenItemClass listSalesmenNameDetail in this.ListSalesmenItemClassList)
            {
                ListSalesmenNameDTS.ListSalesmenItemClassRow detailRow = itemClassDataTable.NewListSalesmenItemClassRow();

                detailRow.SalesmenID = customerTypeID;
                detailRow.SerialID = ++serialID;

                detailRow.ItemClassID = listSalesmenNameDetail.ItemClassID;
                detailRow.Description = listSalesmenNameDetail.Description;

                detailRow.Other = listSalesmenNameDetail.Other;

                detailRow.InActive = listSalesmenNameDetail.InActive;

                itemClassDataTable.AddListSalesmenItemClassRow(detailRow);
            }

            rowsAffected = this.ItemClassTableAdapter.Update(itemClassDataTable);
            if (rowsAffected != this.listSalesmenItemClassList.Count) throw new System.ArgumentException("Insufficient save", "Save detail");


            #endregion <Item Class>


            return true;
        }


        private bool SaveUndo(int salesmenID)
        {
            this.AddressAreaTableAdapter.Delete(salesmenID);
            this.CommodityTableAdapter.Delete(salesmenID);
            this.CustomerTableAdapter.Delete(salesmenID);
            this.ItemClassTableAdapter.Delete(salesmenID);
            

            return true;
        }



        #endregion



        private void RestoreProcedure()
        {
            string queryString;
            string[] queryArray;



            queryString = "     " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";

            queryString = queryString + "       SELECT      CAST(0 AS bit) AS IsSalesmen, 100000 * SalesmenCategoryID AS SalesmenID, Description, 100000 * AncestorID AS AncestorID, EntryDate, '' AS DescriptionOriginal, '' AS JobTitle, '' AS Telephone, '' AS ResidentAddress, ''  AS TypeName, '' AS TitleName " + "\r\n";
            queryString = queryString + "       FROM        ListSalesmenCategory " + "\r\n";


            queryString = queryString + "       UNION ALL " + "\r\n";

            queryString = queryString + "       SELECT      CAST(1 AS bit) AS IsSalesmen, ListSalesmenName.SalesmenID, ListSalesmenName.DescriptionOfficial + ' ' + ListSalesmenName.DescriptionLastName AS Description, 100000 * ListSalesmenName.SalesmenCategoryID AS AncestorID, ListSalesmenName.EntryDate, ListSalesmenName.DescriptionOriginal, ListSalesmenName.JobTitle, ListSalesmenName.Telephone, ListSalesmenName.ResidentAddress, ListSalesmenType.Description AS TypeName, ListSalesmenTitle.Description AS TitleName " + "\r\n";
            queryString = queryString + "       FROM        ListSalesmenName INNER JOIN " + "\r\n";
            queryString = queryString + "                   ListSalesmenType ON ListSalesmenName.SalesmenTypeID = ListSalesmenType.SalesmenTypeID INNER JOIN " + "\r\n";
            queryString = queryString + "                   ListSalesmenTitle ON ListSalesmenName.SalesmenTitleID = ListSalesmenTitle.SalesmenTitleID " + "\r\n";
            
            SQLDatabase.CreateStoredProcedure("ListSalesmenNameListing", queryString);





            queryString = "     @SalesmenID Int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SalesmenCategoryID, SalesmenTypeID, Description, DescriptionZUL, DescriptionDEI, DescriptionOfficial, DescriptionOriginal,  DescriptionLastName, Birthday, HiredDate, JobTitle, ResidentAddress, IdentifyNumber, SecurityID, Telephone, Female, Married, InActive, Other, EMail, SalesmenCommodityAll, SalesmenTitleID, ISNULL(EmployeePicture,'') AS EmployeePicture, EntryDate, UserID, UserOrganizationID " + "\r\n";
            queryString = queryString + "       FROM        ListSalesmenName " + "\r\n";
            queryString = queryString + "       WHERE       SalesmenID = @SalesmenID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenNameSelect", queryString);


            queryString = "     @SalesmenCategoryID int, @SalesmenTypeID int, @Description nvarchar(100), @DescriptionZUL nvarchar(100), @DescriptionDEI nvarchar(100), @DescriptionOfficial nvarchar(100), @DescriptionOriginal nvarchar(100), @DescriptionLastName nvarchar(100), @Birthday datetime, @HiredDate datetime, @JobTitle nvarchar(100), @ResidentAddress nvarchar(150), @IdentifyNumber nvarchar(60), @SecurityID nvarchar(60), @Telephone nvarchar(60), @Female bit, @Married bit, @InActive bit, @Other nvarchar(100), @EMail nvarchar(100), @SalesmenCommodityAll bit, @SalesmenTitleID int, @EmployeePicture nvarchar(50), @EntryDate datetime, @UserID int, @UserOrganizationID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       INSERT INTO ListSalesmenName (SalesmenCategoryID, SalesmenTypeID, Description, DescriptionZUL, DescriptionDEI, DescriptionOfficial, DescriptionOriginal,  DescriptionLastName, Birthday, HiredDate, JobTitle, ResidentAddress, IdentifyNumber, SecurityID, Telephone, Female, Married, InActive, Other, EMail, SalesmenCommodityAll, SalesmenTitleID, EmployeePicture, EntryDate, UserID, UserOrganizationID) VALUES (@SalesmenCategoryID, @SalesmenTypeID, @Description, @DescriptionZUL, @DescriptionDEI, @DescriptionOfficial, @DescriptionOriginal,  @DescriptionLastName, @Birthday, @HiredDate, @JobTitle, @ResidentAddress, @IdentifyNumber, @SecurityID, @Telephone, @Female, @Married, @InActive, @Other, @EMail, @SalesmenCommodityAll, @SalesmenTitleID, @EmployeePicture, @EntryDate, @UserID, @UserOrganizationID) " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SalesmenCategoryID, Description, DescriptionOfficial, DescriptionOriginal, InActive, EntryDate, UserID, UserOrganizationID FROM ListSalesmenName WHERE SalesmenID = SCOPE_IDENTITY() " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenNameInsert", queryString);


            queryString = "     @SalesmenID int, @SalesmenCategoryID int, @SalesmenTypeID int, @Description nvarchar(100), @DescriptionZUL nvarchar(100), @DescriptionDEI nvarchar(100), @DescriptionOfficial nvarchar(100), @DescriptionOriginal nvarchar(100), @DescriptionLastName nvarchar(100), @Birthday datetime, @HiredDate datetime, @JobTitle nvarchar(100), @ResidentAddress nvarchar(150), @IdentifyNumber nvarchar(60), @SecurityID nvarchar(60), @Telephone nvarchar(60), @Female bit, @Married bit, @InActive bit, @Other nvarchar(100), @EMail nvarchar(100), @SalesmenCommodityAll bit, @SalesmenTitleID int, @EmployeePicture nvarchar(50), @EntryDate datetime, @UserID int, @UserOrganizationID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       UPDATE      ListSalesmenName SET SalesmenCategoryID = @SalesmenCategoryID, SalesmenTypeID = @SalesmenTypeID, Description = @Description, DescriptionZUL = @DescriptionZUL, DescriptionDEI = @DescriptionDEI, DescriptionOfficial = @DescriptionOfficial, DescriptionOriginal = @DescriptionOriginal, DescriptionLastName = @DescriptionLastName, Birthday = @Birthday, HiredDate = @HiredDate, JobTitle = @JobTitle, ResidentAddress = @ResidentAddress, IdentifyNumber = @IdentifyNumber, SecurityID = @SecurityID, Telephone = @Telephone, Female = @Female, Married = @Married, InActive = @InActive, Other = @Other, EMail = @EMail, SalesmenCommodityAll = @SalesmenCommodityAll, SalesmenTitleID = @SalesmenTitleID, EmployeePicture = @EmployeePicture, EntryDate = @EntryDate, UserID = @UserID, UserOrganizationID = @UserOrganizationID WHERE SalesmenID = @SalesmenID " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, Description, EntryDate, UserID, UserOrganizationID FROM ListSalesmenName WHERE SalesmenID = @SalesmenID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenNameUpdate", queryString);


            queryString = " @SalesmenID int ";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       DELETE FROM ListSalesmenName WHERE SalesmenID = @SalesmenID " + "\r\n";
            SQLDatabase.CreateStoredProcedure("ListSalesmenNameDelete", queryString);




            //ListSalesmenAddressArea

            queryString = " @SalesmenID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, AddressAreaID, Description, Other, InActive " + "\r\n";
            queryString = queryString + "       FROM        ListSalesmenAddressArea " + "\r\n";
            queryString = queryString + "       WHERE       SalesmenID = @SalesmenID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenAddressAreaSelect", queryString);


            queryString = " @SalesmenID int, @SerialID int,	@AddressAreaID int, @Description nvarchar(100), @Other nvarchar(100), @InActive bit " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       INSERT INTO ListSalesmenAddressArea (SalesmenID, SerialID, AddressAreaID, Description, Other, InActive) VALUES (@SalesmenID, @SerialID, @AddressAreaID, @Description, @Other, @InActive) " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, AddressAreaID, Description, Other, InActive FROM ListSalesmenAddressArea WHERE (SalesmenID = @SalesmenID) AND (SerialID = @SerialID) " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenAddressAreaInsert", queryString);


            queryString = " @SalesmenID int, @SerialID int,	@AddressAreaID int, @Description nvarchar(100), @Other nvarchar(100), @InActive bit " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       UPDATE      ListSalesmenAddressArea SET AddressAreaID = @AddressAreaID, Description = @Description, Other = @Other, InActive = @InActive WHERE SalesmenID = @SalesmenID AND SerialID = @SerialID " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, AddressAreaID, Description, Other, InActive FROM ListSalesmenAddressArea WHERE SalesmenID = @SalesmenID AND SerialID = @SerialID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenAddressAreaUpdate", queryString);


            queryString = " @SalesmenID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       DELETE FROM ListSalesmenAddressArea WHERE SalesmenID = @SalesmenID " + "\r\n";
            SQLDatabase.CreateStoredProcedure("ListSalesmenAddressAreaDelete", queryString);



            //ListSalesmenCommodity       

            queryString = " @SalesmenID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, CommodityID, Description, Other, InActive " + "\r\n";
            queryString = queryString + "       FROM        ListSalesmenCommodity " + "\r\n";
            queryString = queryString + "       WHERE       SalesmenID = @SalesmenID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenCommoditySelect", queryString);


            queryString = " @SalesmenID int, @SerialID int,	@CommodityID int, @Description nvarchar(100), @Other nvarchar(100), @InActive bit " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       INSERT INTO ListSalesmenCommodity (SalesmenID, SerialID, CommodityID, Description, Other, InActive) VALUES (@SalesmenID, @SerialID, @CommodityID, @Description, @Other, @InActive) " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, CommodityID, Description, Other, InActive FROM ListSalesmenCommodity WHERE (SalesmenID = @SalesmenID) AND (SerialID = @SerialID) " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenCommodityInsert", queryString);


            queryString = " @SalesmenID int, @SerialID int,	@CommodityID int, @Description nvarchar(100), @Other nvarchar(100), @InActive bit " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       UPDATE      ListSalesmenCommodity SET CommodityID = @CommodityID, Description = @Description, Other = @Other, InActive = @InActive WHERE SalesmenID = @SalesmenID AND SerialID = @SerialID " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, CommodityID, Description, Other, InActive FROM ListSalesmenCommodity WHERE SalesmenID = @SalesmenID AND SerialID = @SerialID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenCommodityUpdate", queryString);


            queryString = " @SalesmenID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       DELETE FROM ListSalesmenCommodity WHERE SalesmenID = @SalesmenID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenCommodityDelete", queryString);


            //ListSalesmenCustomer

            queryString = " @SalesmenID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, CustomerID, Description, Other, InActive " + "\r\n";
            queryString = queryString + "       FROM        ListSalesmenCustomer " + "\r\n";
            queryString = queryString + "       WHERE       SalesmenID = @SalesmenID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenCustomerSelect", queryString);


            queryString = " @SalesmenID int, @SerialID int,	@CustomerID int, @Description nvarchar(100), @Other nvarchar(100), @InActive bit " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       INSERT INTO ListSalesmenCustomer (SalesmenID, SerialID, CustomerID, Description, Other, InActive) VALUES (@SalesmenID, @SerialID, @CustomerID, @Description, @Other, @InActive) " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, CustomerID, Description, Other, InActive FROM ListSalesmenCustomer WHERE (SalesmenID = @SalesmenID) AND (SerialID = @SerialID) " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenCustomerInsert", queryString);


            queryString = " @SalesmenID int, @SerialID int,	@CustomerID int, @Description nvarchar(100), @Other nvarchar(100), @InActive bit " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       UPDATE      ListSalesmenCustomer SET CustomerID = @CustomerID, Description = @Description, Other = @Other, InActive = @InActive WHERE SalesmenID = @SalesmenID AND SerialID = @SerialID " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, CustomerID, Description, Other, InActive FROM ListSalesmenCustomer WHERE SalesmenID = @SalesmenID AND SerialID = @SerialID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenCustomerUpdate", queryString);


            queryString = " @SalesmenID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       DELETE FROM ListSalesmenCustomer WHERE SalesmenID = @SalesmenID " + "\r\n";
            SQLDatabase.CreateStoredProcedure("ListSalesmenCustomerDelete", queryString);


            //ListSalesmenItemClass

            queryString = " @SalesmenID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, ItemClassID, Description, Other, InActive " + "\r\n";
            queryString = queryString + "       FROM        ListSalesmenItemClass " + "\r\n";
            queryString = queryString + "       WHERE       SalesmenID = @SalesmenID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenItemClassSelect", queryString);


            queryString = " @SalesmenID int, @SerialID int,	@ItemClassID int, @Description nvarchar(100), @Other nvarchar(100), @InActive bit " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       INSERT INTO ListSalesmenItemClass (SalesmenID, SerialID, ItemClassID, Description, Other, InActive) VALUES (@SalesmenID, @SerialID, @ItemClassID, @Description, @Other, @InActive) " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, ItemClassID, Description, Other, InActive FROM ListSalesmenItemClass WHERE (SalesmenID = @SalesmenID) AND (SerialID = @SerialID) " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenItemClassInsert", queryString);


            queryString = " @SalesmenID int, @SerialID int,	@ItemClassID int, @Description float, @Other nvarchar(100), @InActive bit " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       UPDATE      ListSalesmenItemClass SET ItemClassID = @ItemClassID, Description = @Description, Other = @Other, InActive = @InActive WHERE SalesmenID = @SalesmenID AND SerialID = @SerialID " + "\r\n";
            queryString = queryString + "       SELECT      SalesmenID, SerialID, ItemClassID, Description, Other, InActive FROM ListSalesmenItemClass WHERE SalesmenID = @SalesmenID AND SerialID = @SerialID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListSalesmenItemClassUpdate", queryString);


            queryString = " @SalesmenID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       DELETE FROM ListSalesmenItemClass WHERE SalesmenID = @SalesmenID " + "\r\n";
            SQLDatabase.CreateStoredProcedure("ListSalesmenItemClassDelete", queryString);



            /// <summary>
            /// Check for editable
            /// </summary>
            queryArray = new string[4];
            queryArray[0] = "   SELECT      TOP 1 SalesmenID FROM ListSalesmenCategory WHERE SalesmenID = @FindIdentityID ";
            queryArray[1] = "   SELECT      TOP 1 SalesmenID FROM ListCustomerName WHERE SalesmenID = @FindIdentityID ";
            queryArray[2] = "   SELECT      TOP 1 SalesmenID FROM QuotaMaster WHERE SalesmenID = @FindIdentityID  ";
            queryArray[3] = "   SELECT      TOP 1 SalesmenID FROM InMarketMaster WHERE SalesmenID = @FindIdentityID  ";

            SQLDatabase.CreateProcedureToCheckExisting("ListSalesmenNameEditable", queryArray);
        }
    }
}
